#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"

namespace DictNamespace
{
    std::string sep = ": ";
    std::string default_dict_path = "./Dict.txt";
    class Dict
    {
    private:
        void Load()
        {
            std::ifstream in(_dict_path); // 打开配置文件
            if (!in.is_open())
            {
                LOG(FATAL, "open %s failed", _dict_path.c_str());
                exit(-1);
            }

            // 打开文件成功，读取[单词: 中文]
            std::string line;
            while (std::getline(in, line))
            {
                if (line.empty())
                    continue; // 提取到空行重新提取
                auto pos = line.find(':');
                if (pos == std::string::npos)
                    continue;                           // 不符合[单词: 中文]格式
                std::string word = line.substr(0, pos); //"appple: 苹果"
                if (word.empty())
                    continue;
                std::string han = line.substr(pos + sep.length());
                if (han.empty())
                    continue;

                _dict.insert(std::make_pair(word, han));
                LOG(DEBUG, "load info, %s: %s", word.c_str(), han.c_str());
            }
        }

    public:
        Dict():_dict_path(default_dict_path)
        {
            Load();
        }
        std::string Translate(const std::string &word, bool &ok)
        {
            auto it = _dict.find(word);
            if (it == _dict.end())
            {
                ok = false; // 结果不可信
                return "未找到";
            }
            ok = true;
            return _dict[word];
        }

    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _dict_path;
    };
}
